package com.atguigu.gmall.payment.receiver;

import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.payment.service.PaymentService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author atguigu-mqx
 * @Description TODO
 * @Date 2023/9/8 9:39
 * @Version 1.0
 */
@Component
@Slf4j
public class PaymentReceiver {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private OrderFeignClient orderFeignClient;

    /**
     * 监听消息--- rabbitmq --- 消息不丢失，积压，幂等性{setnx,field}，顺序. 消息持久化.
     * @param orderId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_PAYMENT_CLOSE,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_CLOSE),
            key = {MqConst.ROUTING_PAYMENT_CLOSE}
    ))
    public void paymentClose(Long orderId, Message message, Channel channel){
        try {
            //  判断orderId
            if (null != orderId){
                OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
                if (null != orderInfo){
                    //  获取paymentInfo; 利用业务字段 field 判断
                    PaymentInfo paymentInfoQuery = paymentService.getPaymentInfo(orderInfo.getOutTradeNo(), PaymentType.ALIPAY.name());
                    //  交易记录状态。 paymentInfoQuery.getPaymentStatus()==UNPAID CLOSED
                    if (null != paymentInfoQuery && !"CLOSED".equals(paymentInfoQuery.getPaymentStatus())){
                        paymentService.closePayment(orderId);
                        //  paymentService.closePayment(paymentInfoQuery.getId());
                    }
                }
            }
        } catch (Exception e) {
            //  记录消息 insert into msg values(?,?,?);
            log.error(orderId+"关闭交易记录失败");
            e.printStackTrace();
        }
        //  手动签收
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
